package com.kum.controller;

import com.alibaba.fastjson.JSONObject;
import com.kum.domain.AjaxResult;
import com.kum.domain.entity.LoginUser;
import com.kum.domain.entity.SysUser;
import com.kum.domain.entity.SysUserInfo;
import com.kum.service.SysUserInfoService;
import com.kum.service.SysUserService;
import com.kum.utils.JwtUtil;
import com.kum.utils.RequestUtils;
import com.kum.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @version V1.0
 * @Package com.kum.controller
 * @auhter 枯木Kum
 * @date 2021/4/25-1:56 PM
 */

@Api(tags = {"用户操作接口"})
@RestController
@RequestMapping("/system/user")
public class UserController {

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysUserInfoService userInfoService;


    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody JSONObject jsonObject) {
        String userName = jsonObject.getString("userName");
        String password = jsonObject.getString("password");
        if (userName == null || password == null) {
            return AjaxResult.error("用户名或密码不得为空");
        }
        SysUser user = userService.login(userName, password);
        if (user == null) {
            return AjaxResult.error("用户名或密码错误");
        }
        SysUserInfo userInfo = userInfoService.findByUserId(user.getId());
        JSONObject resultObject = new JSONObject();
        resultObject.put("info", userInfo);
        resultObject.put("token", JwtUtil.sign(new LoginUser().toBuilder()
                .id(user.getId())
                .userName(user.getUserName())
                .info(userInfo)
                .build()));


        return AjaxResult.success(resultObject);
    }


    @ApiOperation(value = "注册账号")
    @PostMapping("/register")
    public AjaxResult register(@Validated @RequestBody SysUser sysUser) {
        if (userService.findByUserName(sysUser.getUserName()) != null) {
            return AjaxResult.error("该账户已注册");
        }
        userService.save(sysUser);
        return AjaxResult.success();
    }

    @GetMapping("/t")
    public void t(@RequestParam("loginUser") String loginUser) {
        System.out.println(loginUser);
    }


}
